import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { ConfigEnv, UserConfigExport, loadEnv } from 'vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import DefineOptions from 'unplugin-vue-define-options/vite'
// elemetplus 组件按需导入(减小项目打包体积)
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// https://vitejs.dev/config/
// command 检测开发环境
export default defineConfig(
  ({ command, mode }: ConfigEnv): UserConfigExport => {
    // 获取各种环境下对应的变量
    let env = loadEnv(mode, process.cwd())
    return {
      plugins: [
        vue(),
        // setup 的name 属性生效
        VueSetupExtend(),
        // 作用去百度 或者详见，menu组件
        DefineOptions(),
        createSvgIconsPlugin({
          iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
          symbolId: 'icon-[dir]-[name]',
        }),
        viteMockServe({
          localEnabled: command === 'serve', // 开发阶段能使用mockjs
        }),
        AutoImport({
          resolvers: [ElementPlusResolver()],
        }),
        Components({
          resolvers: [ElementPlusResolver()],
        }),
      ],
      // tsconfig.json 也需要配置
      resolve: { alias: {
        '@': path.resolve('./src') ,
        // 'video.js': 'video.js/dist/video.cjs.js'
      } },
      // scss 配置
      css: {
        preprocessorOptions: {
          scss: {
            javascriptEnabled: true,
            additionalData: '@import "./src/styles/variable.scss";', //scss 全局变量的配置
          },
        },
      },
      // 代理跨域
      server: {
        proxy: {
          [env.VITE_APP_BASE_API]: {
            target: env.VITE_SERVE,
            // 需要代理跨域
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, ''),
          },
        },
      },
    }
  },
)
